<?php
class Mail_Model_Send extends Promotor_Model_Abstract {

	/**
	 * @var array
	 */
	protected $_data = array();

	/**
	 * @return void
	 */
	public function setData(array $data) {
		$this->_data = $data;
	}

	/**
	 * @param mixed $name
	 * @return unknown_type
	 */
	public function getData($name = null) {
		if (null === $data) {
			return $this->_data;
		}

		return isset($this->_data[$name]) ? $this->_data[$name] : $name;
	}
	
	/**
	 * @param array $data
	 * @param string $content
	 * @return void
	 */
	public function send(array $data, $content) {
		$mail = new Zend_Mail();
		$validator = new Zend_Validate_EmailAddress();

		if (!$validator->isValid(@$data['recipent'])) {
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('No reciver');
			return;
		}
		if (!$validator->isValid(@$data['sender'])) {
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('No sender');
			return;
		}
		if (!strlen(@$data['subject'])) {
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('No subject');
			return;
		}
		if (empty($content)) {
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('No content');
			return;
		}
		
		$this->setData($data);

		$mail->addTo($data['recipent'], @$data['recipent_name']);
		$mail->setFrom($data['sender'], @$data['sender_name']);

		$subject = preg_replace('/{{([^}}]+)}}/e', "\$this->getData('$1')", $data['subject']);
		$content = preg_replace('/{{([^}}]+)}}/e', "\$this->getData('$1')", $content);
		$content = nl2br($content);

		$mail->setSubject($subject);
		$mail->setBodyHtml($content, 'utf-8');

		try {
			$mail->send();
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Mail_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
		}
	}

	/**
	 * @param array $data
	 * @return void
	 */
	public function sendQueue(array $array) {
		foreach ($array as $data) {
			if (is_array($data)) {
				$this->send((array) $data, @$data['content']);
			}
		}
	}
}